<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\Menu;
use yii\db\Query;
use yii\db\Command;
use yii\helpers\Url;
use yii\data\Pagination;

class MenuController extends \app\base\Controller
{
    // 菜单列表
    public function actionIndex()
    {
       $Ydb        = Yii::$app->adminDb;
       $query      = new \yii\db\Query();
       $res        = $query->from('menu')->orderBy('parent_id asc,is_state desc,order_num desc')->all($Ydb);
       $menu       = array();
       if ($res) {
            foreach ($res as $k=>$v) {
                $v['is_state']  = $v['is_state'] == 1 ? '有效' : '无效';
                $v['menu_type'] = $v['menu_type'] == 1 ? '前台' : '后台';
                if ($v['parent_id'] == 0) {
                    $menu[$v['id']]  = $v;
                } else {
                    $menu[$v['parent_id']]['_child'][]  = $v;
                }
            }
       }
       $del_url = Url::toRoute('/menu/del').'?del_id=';
       $up_url = '/menu/update?up_id=';
       return $this->render('index', ['menu'=>$menu, 'del_url'=>$del_url, 'up_url'=>$up_url]);
    }

    // 添加Form
    public function actionAdd()
    {
        $Ydb        = Yii::$app->adminDb;
        $query      = new \yii\db\Query();
        $sub_url    = '/menu/sub';
        
        // 获取模块相关的信息 yumao add 
        $params = Yii::$app->params;
        
        $web_list       = array(); // 模块信息
        $web_list_V = array(); // 保存临时的信息
        foreach ($params['sites'] as $paramsV) {
            $web_list_V['module_id'] = isset($paramsV['module_id']) ?  $paramsV['module_id'] : 0;
            $web_list_V['name'] = isset($paramsV['name']) ?  $paramsV['name'] : '';
            $web_list[] = $web_list_V;
        }
        // 模块相关结束
        
        
       
        $sel_arr    = array(array('id' => 0, 'menu_name' => '一级菜单'));
        $csrf       = Yii::$app->request->getCsrfToken();
        $res        = $query->select('id,menu_name')->from('menu')->where('parent_id=0 and module_id = '.$params['sites']['sys_set']['module_id'])->all($Ydb); // 只显示系统管理模块的
        if ($res) {
            $sel_arr = array_merge($sel_arr, $res);
        }
        return $this->render('add', ['sub_url'=>$sub_url, 'csrf'=>$csrf, 'sel_arr'=>$sel_arr,'web_list'=>$web_list]);
    }
    
    /**
     *  通过ajax获取menu数据
     */
    public function actionAjaxGetModule()
    {
        
        // 根据module_id 获取相关的数据
        $module_id = Yii::$app->request->post('module_id');
        
        // 查询相关数据
        $Ydb        = Yii::$app->adminDb;
        $query      = new \yii\db\Query();
        $sel_arr    = array(array('id' => 0, 'menu_name' => '一级菜单'));
        $res        = $query->select('id,menu_name')->from('menu')->where('parent_id=0 and module_id = '.$module_id)->all($Ydb); // 只显示系统管理模块的
        if ($res) {
            $sel_arr = array_merge($sel_arr, $res);
        }
        echo json_encode($sel_arr);
        exit;
        // echo '<pre>';
        // var_dump($res);
        // exit;
    }
    
    // 添加,修改保存
    public function actionSub()
    {
        $val        = Yii::$app->request->post('Menu');
        $Ydb        = \Yii::$app->adminDb;
        $in_arr['parent_id']       = $val['parent_id'];
        $in_arr['menu_ctl']        = $val['menu_ctl'];
        $in_arr['menu_name']       = $val['menu_name'];
        $in_arr['menu_act']        = $val['menu_act'];
        $in_arr['menu_type']       = 0;
        
        // yumao add 所属模块id值
        $in_arr['module_id'] = intval($val['module_id']);
        $in_arr['is_state']        = isset($val['is_state'])?intval($val['is_state']):0;
        $in_arr['order_num']       = isset($val['order_num'])?intval($val['order_num']):0;
        $id                        = isset($val['id'])?intval($val['id']):false;
        $no_empty = array('menu_name','menu_ctl');
        foreach ($no_empty as $k => $v) {
            if (empty($in_arr[$v])) {
                $this->sysMsg('提示', '数据不能为空!', $params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页', 'url'=>'javascript:history.go(-1)'] ] ]);
            }
        }

        $query = new \yii\db\Query();
        if ($id) {
            
            // yumao 修改只要不是在父菜单不相同则可以同名
            $res        = $query->from('menu')->where('menu_name=\''.$in_arr['menu_name'].'\' and module_id = '.$in_arr['module_id'].' and parent_id = '.$in_arr['parent_id'].' and id <>'.$id)->one($Ydb);
            if (intval($in_arr['parent_id']) > 0) {
                $p_res  = $query->from('menu')->where('menu_ctl=\''.$in_arr['menu_ctl'].'\' and menu_act=\''.$in_arr['menu_act'].'\' and id <>'.$id)->one($Ydb);
            }
        } else {
            $res = $query->from('menu')->where('menu_name=\''.$in_arr['menu_name'].'\' and module_id = '.$in_arr['module_id'].' and parent_id = '.$in_arr['parent_id'])->one($Ydb);
            if (intval($in_arr['parent_id']) > 0) {
                $p_res  = $query->from('menu')->where('menu_ctl=\''.$in_arr['menu_ctl'].'\' and menu_act=\''.$in_arr['menu_act'].'\'')->one($Ydb);
            }
        }
        
        if (isset($p_res) && $p_res) {
           $this->sysMsg('提示', 'Error:菜单有重叠!', $params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页', 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        
        if ($res) {
           $this->sysMsg('提示', '菜单名已存在!', $params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页', 'url'=>'javascript:history.go(-1)'] ] ]);
        } else {
            if ($id) {
                $old_arr = $query->from('menu')->where(['id'=>$id])->one($Ydb);
                $Ydb->createCommand()->update('menu', $in_arr, 'id=' . $id)->execute();
                $this->made_menu_cache();
                $change_menu = array_diff($in_arr,$old_arr);
                $obj = new Menu();
                if (!empty($change_menu) || $in_arr['is_state'] != $old_arr['is_state']) {
                     yii::$app->helper->adminlog($id,
                    [
                        'action'    => '修改',
                        'model'     => $obj,
                        'newData'   => $in_arr,
                        'oldData'   => $old_arr
                    ],
                    'app\models\MenuLog'
                    );
                    $this->sysMsg('提示', '修改成功!', $params = ['type' => 'success', 'links' => [ ['name'=>'返回上一页', 'url'=>'/menu/index'] ] ]);
                } else {
                    $this->sysMsg('提示', '没有任何修改!', $params = ['type' => 'success', 'links' => [ ['name'=>'返回上一页', 'url'=>'/menu/index'] ] ]);
                }
            } else {
                $Ydb->createCommand()->insert('menu', $in_arr)->execute();
                $InsertId = $Ydb->getLastInsertID();
                $this->made_menu_cache();
                $obj = new Menu();
                yii::$app->helper->adminlog(
                    $InsertId,
                    [
                        'action'    => '添加',
                        'model'     => $obj,
                        'newData'   => $in_arr,
                    ],
                    'app\models\MenuLog'
                );
                $this->sysMsg('提示', '添加成功!');
            }
        }
    }
    
    // 更新
    public function actionUpdate()
    {
        $Ydb        = Yii::$app->adminDb;
        $query      = new \yii\db\Query();
        $up_id      = intval(Yii::$app->request->get('up_id'));
        if ($up_id == '' || $up_id == 0) {
            $this->sysMsg('提示', 'Error:数据有误!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $up_res = $query->select('*')->from('menu')->where('id='.$up_id)->one($Ydb);
        if (!$up_res) {
            $this->sysMsg('提示', 'Error:数据不存在!', $params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页', 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $sub_url    = '/menu/sub';
        // yumao add 
        // 获取当前节点所属模块和父节点
        $menu_info = $query->select('parent_id,module_id')->from('menu')->where('id = '.$up_id )->all($Ydb);
        $menu_info = $menu_info[0];
       
        // 获取模块相关的信息 yumao add 
        
        $params = Yii::$app->params;
        
        $web_list       = array(); // 模块信息
        $web_list_V = array(); // 保存临时的信息
        foreach ($params['sites'] as $paramsV) {
            $web_list_V['module_id'] = isset($paramsV['module_id']) ?  $paramsV['module_id'] : 0;
            $web_list_V['name'] = isset($paramsV['name']) ?  $paramsV['name'] : '';
            if ($paramsV['module_id'] == $menu_info['module_id']) { // 说明是当前模块
                $web_list_V['selected'] = 1;
            } else {
                $web_list_V['selected'] = 0;
            }
            $web_list[] = $web_list_V;
        }
        // 模块相关结束
        
        // 获取当前模块下的所有一级节点
        $sel_arr    = array(array('id' => 0, 'menu_name' => '一级菜单'));
        $csrf       = Yii::$app->request->getCsrfToken();
        $res        = $query->select('id, menu_name')->from('menu')->where('parent_id=0 and module_id = '.$menu_info['module_id'])->all($Ydb);
        if ($res) {
            $sel_arr = array_merge($sel_arr,$res);
        }
        return $this->render('update', ['sub_url'=>$sub_url, 'csrf'=>$csrf, 'sel_arr'=>$sel_arr, 'up_res'=>$up_res,'web_list'=>$web_list]);
    }
    
    // 删除
    public function actionDel()
    {
        $Ydb        = Yii::$app->adminDb;
        $query      = new \yii\db\Query();
        $del_id     = intval(Yii::$app->request->get('del_id'));
        $rtn_arr    = array();
        if ($del_id==0 || $del_id == '') {
            $rtn_arr['_state']  = 'error';
            $rtn_arr['_msg']    = '数据有误';
            echo json_encode($rtn_arr);
            exit;
        }

        $del_res = $query->select('*')->from('menu')->where('parent_id='. $del_id)->one($Ydb);
        if ($del_res) {
            $rtn_arr['_state']  = 'error';
            $rtn_arr['_msg']    = '此菜单下还有下级菜单,请先修改下级到其它菜单或删除下级菜单';
        } else {
            $Ydb->createCommand()->delete('menu', 'id = '.$del_id)->execute();
            $this->made_menu_cache();
            $rtn_arr['_state']  = 'ok';
            $rtn_arr['_msg']    = '删除成功';
            $obj = new Menu();
            yii::$app->helper->adminlog(
                $del_id, 
                [
                    'model' => $obj, 
                    'action' => '删除',
                ], 
                'app\models\MenuLog'
            );	
        }
        echo json_encode($rtn_arr);
        exit;
    }
    
    // 日志列表
    public function actionLoglist()
    {
        $MeLog      = new \app\models\MenuLog();
        $count      = $MeLog->find()->count();
        $pageSize   = yii::$app->request->getQueryParam('pagesize');
        $pageSize   = empty($pageSize) ? 10 : intval($pageSize);
        $pages      = new Pagination(['totalCount' => $count, 'defaultPageSize' => $pageSize]);
        $logList    = $MeLog->find()->limit($pages->limit)->offset($pages->offset)->orderBy('id desc')->all();
        return $this->render('loglist', ['logs'=>$logList, 'pages'=>$pages]);
    }
    
}
